package com.boc.langxiang.ui.activity.shop;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.shop.FilterView;
import com.boc.langxiang.contract.shop.ProductListView;
import com.boc.langxiang.entity.bean.DepthInfo;
import com.boc.langxiang.entity.bean.ProductTypeBean;
import com.boc.langxiang.entity.bean.ProductsInfo;
import com.boc.langxiang.entity.request.ProductListRequest;
import com.boc.langxiang.entity.response.ProductListContent2;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.presenter.shop.DepthFilterPresenter;
import com.boc.langxiang.presenter.shop.ProductListPresenter;
import com.boc.langxiang.ui.activity.BaseActivity;
import com.boc.langxiang.ui.dialog.ProductTypePop;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.R.attr.id;

/**
 * 所有产品
 */
public class ProductsAllActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, ProductListView {

    @BindView(R.id.search_mag_icon)
    ImageView searchMagIcon;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.filter_recy)
    RecyclerView filterRecy;
    @BindView(R.id.filter_layout)
    LinearLayout filterLayout;
    @BindView(R.id.search_edt)
    EditText searchEdt;

    private BaseQuickAdapter<ProductListContent2.ResultBean> mAdapter;
    private BaseQuickAdapter<DepthInfo> filterAdapter;

    private int currentPage = 1;

    private ProductListRequest mRequest;
    private ProductListPresenter mPresenter;

    private ProductTypeBean mProductTypeBean;

    private View noMoreView,emptyView;

    private Runnable refreshingRunnable = new Runnable() {
        @Override
        public void run() {
            swipeRefresh.setRefreshing(true);
        }
    };

//    Typeface mTypeFace;

    private DepthFilterPresenter mFilterPresenter;
    private boolean mIsLoadmore;
    private boolean mIsOnRefresh;

    private final int pageSize = 14;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_products_all);
        ButterKnife.bind(this);
        setSupportActionBar(toolBar);
//        mTypeFace = App.getInstance().getOtherTypeface();
        initViews();

    }

    private void initViews() {
        initAdapter();

        swipeRefresh.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter.openLoadAnimation();
        //控制itemview动画是否只在第一次显示
        mAdapter.isFirstOnly(true);
        mAdapter.openLoadMore(pageSize, true);
        mAdapter.setOnLoadMoreListener(this);
        mAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ProductListContent2.ResultBean resultBean = mAdapter.getData().get(position);
                String designer_status = resultBean.getDesigner_status();
                switch (designer_status) {
                    case "2":
                        Intent intent = new Intent(mContext, ProductDetailActivity.class);
                        intent.putExtra("id", resultBean.getId());
                        mContext.startActivity(intent);
                        break;
                    case "3":
                        intent = new Intent(mContext, ProductDetail2Activity.class);
                        intent.putExtra("id", resultBean.getId());
                        mContext.startActivity(intent);
                        break;
                }
            }
        });
        emptyView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);
        mAdapter.setEmptyView(emptyView);
        recyclerView.setAdapter(mAdapter);

        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsOnRefresh) {
                    return true;
                }
                return false;
            }
        });


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        filterRecy.setLayoutManager(linearLayoutManager);
        filterRecy.setAdapter(filterAdapter);

        swipeRefresh.setOnRefreshListener(this);
        noMoreView = getLayoutInflater().inflate(R.layout.view_load_done, recyclerView, false);

        searchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    if (!StringUtil.isEmpty(searchEdt.getText().toString())) {
                        searchProducts(searchEdt.getText().toString());
                    }
                }
                return false;
            }
        });

        initData();
    }

    private void searchProducts(String searchWord) {
        Intent intent = new Intent(this, ProductSearchResultActivity.class);
        intent.putExtra("keyword", searchWord);
        if (mProductTypeBean != null) {
            intent.putExtra("ctype", mProductTypeBean.getId());
        }
        startActivity(intent);
    }

    private void initData() {
        mRequest = new ProductListRequest();
        mRequest.setPage(currentPage);
        mPresenter = new ProductListPresenter(this);

        mFilterPresenter = new DepthFilterPresenter(new FilterView() {
            @Override
            public void getListSuccess(List<DepthInfo> list) {
                filterAdapter.setNewData(list);
                filterAdapter.notifyDataSetChanged();
            }

            @Override
            public void showLoading() {
                showProgressDialog("请稍等");
            }

            @Override
            public void hideLoading() {
                hideDialog();
            }

            @Override
            public void onError(String code, String msg) {
                T.showShort(mContext, msg);
            }
        });
        mFilterPresenter.getFilters();

        onRefresh();
    }


    private void initAdapter() {
        mAdapter = new BaseQuickAdapter<ProductListContent2.ResultBean>(R.layout.product_all_item, new ArrayList<ProductListContent2.ResultBean>()) {
            @Override
            protected void convert(BaseViewHolder helper, ProductListContent2.ResultBean item) {
                helper.setText(R.id.product_title_tv, item.getTitle());
                helper.setText(R.id.price_tv, "￥" + item.getPrice());

                if (item.getPhoto()!=null){
                    PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getPhotourl()
                            , (ImageView) helper.getView(R.id.img_iv));
                }
            }
        };

        filterAdapter = new BaseQuickAdapter<DepthInfo>(R.layout.filter_item, new ArrayList<DepthInfo>()) {
            @Override
            protected void convert(final BaseViewHolder helper, final DepthInfo item) {
                helper.setText(R.id.text, item.getTitle());
                if (helper.getPosition() == 0) {
                    helper.getView(R.id.divider_horizontal).setVisibility(View.GONE);
                }

                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.getMore().size() > 0) {
                            helper.getView(R.id.open_popup).setVisibility(View.VISIBLE);
                            final String title = item.getTitle();
                            ProductTypePop pop = new ProductTypePop(mContext, item.getMore());
                            pop.setOndismissListener(new PopupWindow.OnDismissListener() {
                                @Override
                                public void onDismiss() {
                                    helper.getView(R.id.open_popup).setVisibility(View.GONE);
                                }
                            });
                            pop.show(helper.getConvertView(), new ProductTypePop.OnTypeSelectListener() {
                                @Override
                                public void onSelect(ProductTypeBean bean) {
                                    mProductTypeBean = bean;
                                    if(title.equals("价格")){
                                        mRequest.setCtype(null);
                                        mRequest.setPrice_id(bean.getId());                                  
                                    }else{
                                        mRequest.setCtype(bean.getId());
                                        mRequest.setPrice_id(null);
                                    }
                                    onRefresh();
                                }
                            });
                        }
                    }
                });
            }
        };
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLoadMoreRequested() {
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                if (mIsLoadmore || mIsOnRefresh) {
                    return;
                }
                mIsLoadmore = true;
                int page = currentPage + 1;
                mRequest.setPage(page);
                mPresenter.loadMore(mRequest);

            }
        });
    }

    @Override
    public void onRefresh() {
        if (mIsOnRefresh || mIsLoadmore) {
            hideLoading();
            return;
        }
        mIsOnRefresh = true;
        currentPage = 1;
        mRequest.setPage(1);
        mPresenter.getList(mRequest);
    }

    @Override
    public void getListSuccsee(List<ProductListContent2.ResultBean> list) {
        mIsOnRefresh = false;
        if (list != null && list.size() > 0) {
            mAdapter.setNewData(list);
            mAdapter.notifyDataSetChanged();
            if (list.size()<pageSize){
                mAdapter.addFooterView(noMoreView);
                mAdapter.notifyDataChangedAfterLoadMore(false);
            }
        }else{
            mAdapter.setNewData(new ArrayList<ProductListContent2.ResultBean>());
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void loadMoreSuccess(List<ProductListContent2.ResultBean> list) {
        mIsLoadmore = false;
        if (list != null && list == null) {
            mAdapter.notifyDataChangedAfterLoadMore(false);
            mAdapter.addFooterView(noMoreView);
            return;
        }
        if (list.size() < pageSize) {
            mAdapter.notifyDataChangedAfterLoadMore(list, false);
            mAdapter.addFooterView(noMoreView);
        } else {
            mAdapter.notifyDataChangedAfterLoadMore(list, true);
        }

    }

    @Override
    public void showLoading() {
        swipeRefresh.post(refreshingRunnable);
    }

    @Override
    public void hideLoading() {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(false);
            }
        });

    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, msg);
    }
}
